package com.xxgc.demo.controller.aop;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Author:SJY
 * @Date :2023/10/16 - 10 - 16 - 10:37
 * 通过面向切面，所有请求进入后都会先设置一下数据源
 */
@Aspect
@Component
public class DataSourceMangerAOP {
    //数据源
    private static String source;

    @Value("${spring.datasource.dynamic.primary}")
    public void setSource(String data){
        this.source = data;
    }
    //获取当前数据源
    public static String getSource(){
        return source;
    }

    /**
     * 管理和设置数据源
     */
    @Before("execution (* com.xxgc.demo.controller.*Controller.*(..))")
    public void dataSourceManger(){
        //设置数据源
        DynamicDataSourceContextHolder.push(source);
    }

    /**
     * 修改数据源
     * @param name 数据源名称
     */
    public static void changeSource(String name){
        DynamicDataSourceContextHolder.clear();
        DynamicDataSourceContextHolder.push(name);
        source = name;
    }
}
